package com.basker.pisces.springcloud.signature;

import org.springframework.core.NamedThreadLocal;

import com.basker.ttl.NamedTransmittableThreadLocal;

/**
 * 签名对象的线程上下文存储器
 *
 * <p>
 * 调用的客户端代理类，会负责生成签名并存放到当前存储器中，而发送请求前，会由Feign拦截器负责取出并添加到消息头中
 *
 * @author hangwen
 */
public class SignatureHolder {
    private static final String NAME = SignatureHolder.class.getSimpleName();

    private static final ThreadLocal<Signature> TL_HOLDER = new NamedThreadLocal<>(NAME);
    private static final ThreadLocal<Signature> TTL_HOLDER = new NamedTransmittableThreadLocal<>(NAME);

    /**
     * 清除当前线程上下文中的签名
     */
    public static void clear() {
        TL_HOLDER.remove();
        TTL_HOLDER.remove();
    }

    /**
     * 从当前线程上下文中获取签名
     *
     * @return
     */
    public static Signature getSignature() {
        Signature signature = TL_HOLDER.get();

        if (signature == null) {
            signature = TTL_HOLDER.get();
        }

        return signature;
    }

    /**
     * 将签名存放到当前线程上下文
     *
     * @param signature
     * @param inheritable 如果true，那么当前线程创建的子线程上下文里也可以获取当前存放的签名
     */
    public static void setSignature(Signature signature, boolean inheritable) {
        if (signature == null) {
            return;
        }

        if (inheritable) {
            TTL_HOLDER.set(signature);
            TL_HOLDER.remove();
        } else {
            TL_HOLDER.set(signature);
            TTL_HOLDER.remove();
        }
    }
}
